package com.xinluxinli.caiwu.controller;

import com.xinluxinli.caiwu.entity.EmployeeInfo;
import com.xinluxinli.caiwu.entity.EmployeeInfoVo;
import com.xinluxinli.caiwu.entity.ResponseEntity;
import com.xinluxinli.caiwu.entity.User;
import com.xinluxinli.caiwu.service.EmployeeInfoService;
import com.xinluxinli.caiwu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeInfoService employeeInfoService;

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/customer_list")
    public String customer_list(HttpServletRequest request, String employee, String date, Model model) {
//        if (!userService.cookieLoginCheck(request)){
            List<EmployeeInfoVo> employeeInfos = employeeInfoService.queryEmployeeInfo(employee, date);
            //放在请求域中
            model.addAttribute("emps",employeeInfos);
//        }
        return "customer_list";
    }

    @GetMapping("/customer_add")
    public String customer_add() {
        return "customer_add";
    }


    @PostMapping("/login")
    @ResponseBody
    public ResponseEntity login(@RequestBody User user, HttpServletResponse response) {
        ResponseEntity responseEntity = new ResponseEntity();
        boolean loginCheck = userService.loginCheck(user);
        if (loginCheck){
            String domain = "47.92.114.49";
//            String domain = "127.0.0.1";
            responseEntity.setCode(0);
            Cookie cookieu  =  new Cookie("username",user.getUsername());
            cookieu.setMaxAge(24*3600);
            cookieu.setDomain(domain);
            response.addCookie(cookieu);
            Cookie cookiep  =  new Cookie("password", DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            cookiep.setMaxAge(24*3600);
            cookiep.setDomain(domain);

            response.addCookie(cookiep);
        }else {
            responseEntity.setCode(10001);
        }
        return responseEntity;
    }


    @PostMapping("/addEmployee")
    @ResponseBody
    public ResponseEntity addUser(@RequestBody EmployeeInfoVo employeeInfo) throws ParseException {
        ResponseEntity responseEntity = new ResponseEntity();
        employeeInfoService.addEmployeeInfo(employeeInfo);
        responseEntity.setCode(0);

        return responseEntity;
    }
}
